/*using Stack to implement bracket matching algorithm */

let Stack = require('../util/arrayStack');
let leftBrackets = ['(', '[', '{'];
let rightBrackets = [')', ']', '}'];

let bracketMatching = (str) => {
    let stack = new Stack();
    let res = true;
    str.toString().split('').forEach(ch => {
        if (leftBrackets.indexOf(ch) >= 0) {
            stack.push(ch);
        } else if (rightBrackets.indexOf(ch) >= 0) {
            if (!stack.isEmpty()) {
                let bracket = stack.pop();
                let index = leftBrackets.indexOf(bracket);
                if (!index < 0 || rightBrackets[index] !== ch) {
                    res = false;
                    return;
                }
            } else {
                res = false;
                return;
            }
        }
    });
    if (!res || !stack.isEmpty()) {
        return false;
    }
    return true;
};

module.exports = bracketMatching;
